package com.example.a517;

import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.IOException;

import Util.HttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_response;
    private Button btn_send;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_ok_http);
        tv_response =  findViewById(R.id.tv_response);
        btn_send = findViewById(R.id.send);
        btn_send.setOnClickListener(this);
    }
    private void sendRequestWithHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showResponse(String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_response.setText(responseData);
            }
        });
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send){
            //sendRequestWithHttp();
            String string = HttpUtil.sendHttpRequest("https://www.baidu.com");
            tv_response.setText(string);
        }
    }
}